<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import enterpriseTypeDict from '@/utils/EnterpriseTypeDict.js';
import enterpriseIndustryDict from '@/utils/EnterpriseIndustryDict';
import addressDict from '@/utils/AddressDict';
import { getInfo, submitInfo, updateInfo, getInfoStatus } from '@/api/info';
import { ElMessageBox, ElMessage } from 'element-plus';
import AppSidebar from '@/components/common/AppSidebar.vue';
import { useEnterpriseStore } from '@/stores/enterprise';

const enterpriseStore = useEnterpriseStore();

// 编辑模式状态
const isRecord = ref(false);
const status = ref(0);
const reason = ref('');
const formRef = ref(null);

// 表单数据 TODO: 从后端获取数据
const formData = ref({
    region: '',
    orgCode: '',
    name: '',
    nature: '',
    industry: '',
    industryDesc: '',
    contactName: '',
    address: '',
    postalCode: '',
    phoneNum: '',
    faxNum: '',
    email: '',
});

// 企业性质选项（两级联动）
const companyTypeOptions = ref([]);

// 所属行业选项（两级联动）
const industryOptions = ref([]);

// 联系地址选项（两级联动）
const addressOptions = ref([]);

// 计算状态文本
const statusText = computed(() => {
    switch (status.value) {
        case 0:
            return '未备案';
        case 1:
            return '审核中';
        case 2:
            return '已驳回';
        case 3:
            return '已备案';
        default:
            return '';
    }
});

// 计算状态类型
const statusType = computed(() => {
    switch (status.value) {
        case 0:
            return 'info';
        case 1:
            return 'warning';
        case 2:
            return 'danger';
        case 3:
            return 'success';
        default:
            return 'info';
    }
});

// 计算属性：获取级联选择器的值
const addressCascadeValue = computed({
    get: () => {
        if (!formData.value.region) return [];
        return addressDict.getLevelCodes(formData.value.region);
    },
    set: (value) => {
        if (value && value.length === 3) {
            // 存储最终代码（区级代码）
            formData.value.region = value[2];
        } else {
            formData.value.region = '';
        }
    },
});

const addressCascadeValue2 = computed({
    get: () => {
        if (!formData.value.address) return [];
        return addressDict.getLevelCodes(formData.value.address);
    },
    set: (value) => {
        if (value && value.length === 3) {
            // 存储最终代码（区级代码）
            formData.value.address = value[2];
        } else {
            formData.value.address = '';
        }
    },
});

// 计算属性：获取当前企业类型的显示值（用于级联选择器）
const companyTypeDisplayValue = computed({
    get: () => {
        if (!formData.value.nature) return [];

        const code = formData.value.nature;
        if (enterpriseTypeDict.isValidSecondaryCode(code)) {
            const primaryCode = enterpriseTypeDict.getPrimaryCodeBySecondary(code);
            return [primaryCode, code];
        }
        return [];
    },
    set: (newValue) => {
        if (newValue && newValue.length === 2) {
            // 存储最终的二级代码
            formData.value.nature = newValue[1];
        } else {
            formData.value.nature = null;
        }
    },
});

// 计算属性：获取当前企业类型的显示值（用于级联选择器）
const companyIndustryDisplayValue = computed({
    get: () => {
        if (!formData.value.industry) return [];

        const code = formData.value.industry;
        if (enterpriseIndustryDict.isValidSecondaryCode(code)) {
            const primaryCode = enterpriseIndustryDict.getPrimaryCodeBySecondary(code);
            return [primaryCode, code];
        }
        return [];
    },
    set: (newValue) => {
        if (newValue && newValue.length === 2) {
            // 存储最终的二级代码
            formData.value.industry = newValue[1];
        } else {
            formData.value.industry = null;
        }
    },
});

// 初始化企业类型选项
onMounted(async () => {
    companyTypeOptions.value = enterpriseTypeDict.getCascadeOptions();
    industryOptions.value = enterpriseIndustryDict.getCascadeOptions();
    addressOptions.value = addressDict.getCascadeOptions();

    // 拉取企业信息和备案状态，防止刷新后状态丢失导致显示“未备案”
    try {
        const [infoRes, statusRes] = await Promise.all([getInfo(), getInfoStatus()]);
        const resolvedStatus =
            typeof statusRes?.data === 'number' ? statusRes.data : Number(statusRes?.data);
        status.value = Number.isNaN(resolvedStatus) ? 0 : resolvedStatus;
        isRecord.value = status.value === 1 || status.value === 3;
        enterpriseStore.updateProfileStatus(status.value);

        if (infoRes?.data) {
            formData.value = { ...formData.value, ...infoRes.data };
            reason.value = infoRes.data.reasonReturn || '';
        }
    } catch (error) {
        ElMessage.error(error.message || '获取企业信息失败');
    }

    // 检查状态是否为2，显示消息窗口
    if (status.value === 2) {
      const content = reason.value && reason.value.trim().length > 0
        ? `<div style="line-height:1.6">
             <div>很抱歉，您的备案未通过。</div>
             <div style="margin-top:8px"><strong>退回原因：</strong></div>
             <div style="white-space:pre-wrap;margin-top:4px">${reason.value}</div>
           </div>`
        : `<div style="line-height:1.6">
             <div>很抱歉，您的备案未通过。</div>
             <div style="margin-top:8px;color:#999">未提供退回理由，请联系审核人员了解详情。</div>
           </div>`;
      ElMessageBox.alert(content, '备案未通过', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
      });
    }
});

// 表单验证规则
const rules = reactive({
    nature: [{ required: true, message: '请选择企业性质', trigger: 'change' }],
    industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
    industryDesc: [
        { required: true, message: '请输入主要业务', trigger: 'blur' },
        { min: 5, max: 500, message: '主要业务长度在5-500个字符', trigger: 'blur' },
    ],
    contactName: [
        { required: true, message: '请输入联系人', trigger: 'blur' },
        { min: 2, max: 20, message: '联系人姓名长度在2-20个字符', trigger: 'blur' },
    ],
    address: [{ required: true, message: '请选择联系地址', trigger: 'change' }],
    postalCode: [
        { required: true, message: '请输入邮政编码', trigger: 'blur' },
        { pattern: /^[0-9]{6}$/, message: '邮政编码必须为6位数字', trigger: 'blur' },
    ],
    phoneNum: [
        { required: true, message: '请输入电话号码', trigger: 'blur' },
        { pattern: /^[0-9]{11}$/, message: '电话号码必须为11位数字', trigger: 'blur' },
    ],
    faxNum: [
        { message: '请输入传真', trigger: 'blur' },
        { pattern: /^[0-9-]{6,20}$/, message: '传真格式不正确', trigger: 'blur' },
    ],
    email: [
        {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: '邮箱格式不正确',
            trigger: 'blur',
        },
    ],
});

// 保存表单
const saveForm = async () => {
    // 如果状态为1（审核中），提示无法提交
    if (status.value === 1) {
        ElMessage.warning('审核中，无法提交修改');
        return;
    }

    // 表单验证 - 使用Promise包装以确保验证不通过时完全阻止后续操作
    try {
        // 强制验证所有字段
        await new Promise((resolve, reject) => {
            formRef.value.validate((valid) => {
                if (valid) {
                    resolve();
                } else {
                    ElMessage.error('表单验证失败，请检查所有必填项和格式要求');
                    reject(new Error('表单验证失败'));
                }
            });
        });

        // 验证通过后才显示确认对话框
        console.log('保存表单数据:', formData.value);
        if (status.value === 0 || status.value === 2) {
            await ElMessageBox.confirm('确认提交吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            });

            // 确认提交，调用后端接口
            const submitResult = await submitInfo(formData.value);
            ElMessage.success('提交成功');
            // 刷新状态
            const statusData = await getInfoStatus();
            isRecord.value = statusData.data == 3 || statusData.data == 1 ? true : false;
            status.value = statusData.data;

            // 更新全局状态管理中的备案状态
            enterpriseStore.updateProfileStatus(statusData.data);
        } else if (status.value === 3) {
            await ElMessageBox.confirm('确认更新吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            });

            // 确认更新，调用后端接口
            const updateResult = await updateInfo(formData.value);
            ElMessage.success('更新成功');
            // 刷新状态
            const statusData = await getInfoStatus();
            isRecord.value = statusData.data == 3 || statusData.data == 1 ? true : false;
            status.value = statusData.data;

            // 更新全局状态管理中的备案状态
            enterpriseStore.updateProfileStatus(statusData.data);
        }
    } catch (error) {
        // 捕获验证失败或用户取消确认的情况，不执行后续操作
        console.log('表单提交被阻止:', error.message);
    }
};
</script>

<template>
    <div class="profile-form">
        <el-main class="profile-main">
            <div class="page-header">
                <div class="header-left">
                    <h1 class="page-title">企业备案信息</h1>
                    <div class="page-description">
                        编辑企业信息
                        <el-tag v-if="statusText" :type="statusType" class="ml-2">{{
                            statusText
                        }}</el-tag>
                    </div>
                </div>
            </div>

            <!-- 表单内容 -->
            <div class="form-container">
                <el-form
                    ref="formRef"
                    :model="formData"
                    :rules="rules"
                    label-width="120px"
                    label-position="left"
                >
                    <el-form-item label="所属地区" prop="region">
                        <el-cascader
                            v-model="addressCascadeValue"
                            :options="addressOptions"
                            :disabled="true"
                            placeholder="请选择联系地址"
                            style="width: 100%"
                            change-on-select
                        />
                    </el-form-item>

                    <el-form-item label="社会信用代码" prop="orgCode">
                        <el-input
                            v-model="formData.orgCode"
                            :disabled="true"
                            placeholder="请输入社会信用代码"
                        />
                    </el-form-item>

                    <el-form-item label="企业名称" prop="name">
                        <el-input
                            v-model="formData.name"
                            :disabled="true"
                            placeholder="请输入企业名称"
                        />
                    </el-form-item>

                    <el-form-item label="企业性质" prop="nature">
                        <el-cascader
                            v-model="companyTypeDisplayValue"
                            :options="companyTypeOptions"
                            :disabled="isRecord"
                            placeholder="请选择企业性质"
                            style="width: 100%"
                            change-on-select
                        />
                    </el-form-item>

                    <el-form-item label="所属行业" prop="industry">
                        <el-cascader
                            v-model="companyIndustryDisplayValue"
                            :options="industryOptions"
                            :disabled="isRecord"
                            placeholder="请选择所属行业"
                            style="width: 100%"
                            change-on-select
                        />
                    </el-form-item>

                    <el-form-item label="主要业务" prop="industryDesc">
                        <el-input
                            v-model="formData.industryDesc"
                            :disabled="isRecord"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入主要业务"
                        />
                    </el-form-item>

                    <el-form-item label="联系人" prop="contactName">
                        <el-input v-model="formData.contactName" placeholder="请输入联系人" />
                    </el-form-item>

                    <el-form-item label="联系地址" prop="address">
                        <el-cascader
                            v-model="addressCascadeValue2"
                            :options="addressOptions"
                            placeholder="请选择联系地址"
                            style="width: 100%"
                            change-on-select
                        />
                    </el-form-item>

                    <el-form-item label="邮政编码" prop="postalCode">
                        <el-input v-model="formData.postalCode" placeholder="请输入邮政编码" />
                    </el-form-item>

                    <el-form-item label="电话号码" prop="phoneNum">
                        <el-input v-model="formData.phoneNum" placeholder="请输入电话号码" />
                    </el-form-item>

                    <el-form-item label="传真" prop="faxNum">
                        <el-input v-model="formData.faxNum" placeholder="请输入传真" />
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="formData.email" type="email" placeholder="请输入邮箱" />
                    </el-form-item>
                </el-form>
            </div>

            <!-- 底部保存按钮 -->
            <div class="content-footer">
                <el-button type="primary" @click="saveForm">
                    <div v-if="status === 3">保存</div>
                    <div v-else>提交</div>
                </el-button>
            </div>
        </el-main>
    </div>
</template>

<style scoped lang="scss">
.profile-form {
    display: flex;
    min-height: 100vh;
    background: var(--el-bg-color-page);
    justify-content: center;
}

.profile-main {
    flex: 1;
    padding: 48px 64px;
    overflow: auto;
    background: transparent;
    background-color: var(--el-bg-color-page);
    max-width: 1400px;
    width: 100%;
    margin: 0 auto;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 40px;
    background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
    border-radius: 24px;
    color: white;
    box-shadow: 0 20px 40px -12px rgba(79, 70, 229, 0.3);
}

.header-left {
    flex: 1;
}

.page-title {
    margin: 0 0 8px 0;
    font-size: 28px;
    font-weight: 700;
    color: white;
}

.page-description {
    margin: 0;
    font-size: 14px;
    opacity: 0.9;
    display: flex;
    align-items: center;
}

.ml-2 {
    margin-left: 8px;
}

.form-container {
    flex: 1;
    padding: 32px;
    background-color: white;
    margin: 24px 32px;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.content-footer {
    // background-color: white;
    padding: 16px 32px;
    border-top: 1px solid #e8e8e8;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    position: sticky;
    bottom: 0;
}

.form-section {
    margin-bottom: 24px;
    padding: 32px;
    background: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(20px) saturate(180%);
    border-radius: 20px;
    border: 1px solid rgba(255, 255, 255, 0.8);
    box-shadow:
        0 1px 3px rgba(0, 0, 0, 0.02),
        0 8px 24px rgba(0, 0, 0, 0.04);
    transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);

    &:hover {
        box-shadow:
            0 2px 4px rgba(0, 0, 0, 0.03),
            0 12px 32px rgba(0, 0, 0, 0.06);
    }

    &:last-of-type {
        margin-bottom: 0;
    }
}

.section-header {
    margin-bottom: 28px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--el-border-color-light);

    .section-title {
        font-size: 22px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        letter-spacing: -0.02em;
        margin: 0 0 6px 0;
        line-height: 1.3;
    }

    .section-desc {
        font-size: 14px;
        color: var(--el-text-color-secondary);
        margin: 0;
        letter-spacing: -0.01em;
    }
}

.option-info {
    margin-left: 8px;
    color: var(--el-color-primary);
    cursor: help;
    transition: all 0.2s ease;

    &:hover {
        transform: scale(1.1);
    }
}

.reduction-summary {
    margin-top: 20px;
    border-radius: 14px;
    border: 1px solid var(--el-color-primary-light-7);
    background: var(--el-color-primary-light-9);

    :deep(.el-alert__icon) {
        color: var(--el-color-primary);
    }

    :deep(.el-alert__title) {
        color: var(--el-text-color-primary);
        font-weight: 500;
        letter-spacing: -0.01em;
    }

    :deep(.el-alert__description) {
        color: var(--el-text-color-regular);
        font-size: 13px;
        letter-spacing: -0.01em;
    }
}

.section-actions {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    margin-top: 32px;
    padding-top: 32px;
}

.action-btn {
    height: 44px;
    padding: 0 32px;
    font-size: 15px;
    font-weight: 500;
    letter-spacing: -0.01em;
    border-radius: 12px;
    transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);

    &.action-btn-primary {
        background: var(--el-color-primary);
        border-color: var(--el-color-primary);
        box-shadow:
            0 2px 8px var(--el-color-primary-light-5),
            0 4px 12px var(--el-color-primary-light-7),
            inset 0 1px 1px rgba(255, 255, 255, 0.25);

        &:hover {
            background: var(--el-color-primary-light-3);
            border-color: var(--el-color-primary-light-3);
            transform: translateY(-2px);
            box-shadow:
                0 4px 12px var(--el-color-primary-light-5),
                0 8px 20px var(--el-color-primary-light-7),
                inset 0 1px 1px rgba(255, 255, 255, 0.25);
        }

        &:active {
            transform: scale(0.98);
        }
    }

    &.action-btn-secondary {
        background: var(--el-fill-color-blank);
        backdrop-filter: blur(10px);
        color: var(--el-text-color-primary);
        border: 1px solid var(--el-border-color-light);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);

        &:hover {
            background: var(--el-fill-color);
            border-color: var(--el-border-color);
            color: var(--el-color-primary);
            transform: translateY(-2px);
            box-shadow:
                0 2px 8px rgba(0, 0, 0, 0.04),
                0 4px 12px rgba(0, 0, 0, 0.03);
        }

        &:active {
            transform: scale(0.98);
        }
    }
}

// Element Plus 表单项样式优化
:deep(.el-form-item) {
    margin-bottom: 24px;

    .el-form-item__label {
        color: var(--el-text-color-primary);
        font-weight: 500;
        font-size: 14px;
        letter-spacing: -0.01em;
        line-height: 36px;
    }

    .el-input__wrapper,
    .el-textarea__inner {
        border-radius: 10px;
        border: 1px solid var(--el-border-color);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
        transition: all 0.2s ease;

        &:hover {
            border-color: var(--el-color-primary-light-5);
        }

        &.is-focus {
            border-color: var(--el-color-primary);
            box-shadow:
                0 0 0 3px var(--el-color-primary-light-9),
                0 2px 4px rgba(0, 0, 0, 0.02);
        }
    }

    .el-select {
        width: 100%;
    }

    .el-input-number {
        width: 100%;

        .el-input__wrapper {
            border-radius: 10px;
        }
    }

    .el-date-editor {
        width: 100%;
    }
}

// 下拉选择器样式优化
:deep(.el-select-dropdown) {
    border-radius: 14px;
    border: 1px solid var(--el-border-color-light);
    box-shadow:
        0 4px 16px rgba(0, 0, 0, 0.08),
        0 2px 4px rgba(0, 0, 0, 0.04);

    .el-select-dropdown__item {
        border-radius: 8px;
        margin: 4px 8px;
        padding: 8px 12px;
        transition: all 0.2s ease;

        &:hover {
            background: var(--el-color-primary-light-9);
            color: var(--el-color-primary);
        }

        &.selected {
            background: var(--el-color-primary-light-8);
            color: var(--el-color-primary);
            font-weight: 500;
        }
    }
}

// 响应式设计
@media (max-width: 1400px) {
    .profile-main {
        padding: 40px 48px;
    }
}

@media (max-width: 1024px) {
    .profile-main {
        padding: 32px 24px;
    }

    .form-section {
        padding: 24px;
    }

    .page-header .page-title {
        font-size: 28px;
    }
}
</style>
